<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="关联账户表" prop="accountId">
        <el-input v-model="queryParams.accountId" placeholder="请输入关联账户表" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品代码" prop="productId">
        <el-input v-model="queryParams.productId" placeholder="请输入关联产品表" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      {{ soldOffSelected }}
    </el-form>
    <el-checkbox-group v-model="soldOffSelected" @change="onSoldOffSelectChange">
      <el-checkbox value="Y">Y</el-checkbox>
      <el-checkbox value="N">N</el-checkbox>
    </el-checkbox-group>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['finace']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['finace']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['finace']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['finace']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transactions_fundList" @selection-change="handleSelectionChange" height="600"
      @row-click="onRowClicked">
      <el-table-column type="selection" width="32" align="center" />
      <!-- <el-table-column label="交易唯一标识" align="center" prop="transactionId" /> -->
      <el-table-column label="操作" width="80" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['finace', 'finace:transactions_fund:edit']" title="修改"></el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['finace', 'finace:transactions_fund:remove']" title="删除"></el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <el-table-column label="账户ID" width="80" align="center" prop="accountId">
        <template #default="scope">
          <span>{{accountList.find((x) => x.accountId === scope.row.accountId)?.name}} </span>
        </template>
      </el-table-column>
      <el-table-column label="产品代码" width="80" align="left" prop="productId" show-overflow-tooltip />
      <el-table-column label="产品名称" width="160" align="left" prop="productId" show-overflow-tooltip>
        <template #default="scope">
          <span>{{productList.find((x) => x.productCode === scope.row.productId)?.productName}} </span>
        </template>
      </el-table-column>
      <el-table-column label="交易提交日期" align="center" prop="submitTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易确认日期" align="center" prop="confirmDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.confirmDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易类型" width="80" align="left" prop="type" show-overflow-tooltip />
      <el-table-column label="单价" width="80" align="left" prop="price">
        <template #default="scope">
          <span> ¥ {{ scope.row.price?.toFixed(4) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="100" align="right" prop="quantity" show-overflow-tooltip>
        <template #default="scope">
          <span> {{ scope.row.quantity?.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" width="100" align="right" prop="amount">
        <template #default="scope">
          <span> ¥{{ scope.row.amount?.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手续费" width="80" align="right" prop="fee">
        <template #default="scope">
          <span> ¥{{ scope.row.fee?.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="交易价格日期" align="center" prop="priceDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.priceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="资金流向/来源" width="120" align="left" prop="transWith" show-overflow-tooltip />
      <el-table-column label="已经清仓" width="120" align="left" prop="soldOff" show-overflow-tooltip />
      <el-table-column label="备注" align="left" prop="comment" show-overflow-tooltip />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改个人持仓记录对话框 -->
    <el-dialog v-model="open" width="500px" append-to-body>
      <template #header>
        {{ title }} <el-checkbox v-model="autoCalcAmount">关联计算</el-checkbox>
        <el-radio-group v-model="dividendType" size="small" @change="onRadioChange" v-show="isDividend">
          <el-radio value="cash">现金分红</el-radio>
          <el-radio value="fund">分红再投</el-radio>
        </el-radio-group>
      </template>
      <el-form ref="transactions_fundRef" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入关联用户表" readonly />
        </el-form-item>
        <el-form-item label="账户" prop="accountId">
          <el-select v-model="form.accountId" placeholder="请选择账户">
            <el-option v-for="item in accountList" :key="item.accountId" :label="item.name"
              :value="item.accountId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入关联产品表" readonly />
        </el-form-item>
        <el-form-item label="产品名称" prop="productId">
          <el-select v-model="form.productId" placeholder="请输入关联产品表" @change="productIdChanged">
            <el-option v-for="item in productList" :key="item.productId" :label="item.productName"
              :value="item.productCode" />
          </el-select>
        </el-form-item>

        <el-form-item label="交易类型" prop="type">
          <el-select v-model="form.type" placeholder="请输入关联产品表" @change="onTradeTypeChanged">
            <el-option
              v-for="item in [{ id: 'BUY', label: '买入' }, { id: 'SELL', label: '卖出' }, { id: 'DIVIDEND', label: '分红' }]"
              :key="item.id" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="交易提交日期" prop="submitTime">
          <el-date-picker clearable v-model="form.submitTime" type="datetime"
            :default-time="new Date(2000, 1, 1, 10, 0, 0)" placeholder="请选择交易提交日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交易确认时间" prop="confirmDate">
          <el-date-picker clearable v-model="form.confirmDate" type="datetime"
            :default-time="new Date(2000, 1, 1, 10, 0, 0)" placeholder="请选择交易确认的时间" value-format="YYYY-MM-DD"
            @change=confirmDateChange>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价" @input="onPriceInput" :clearable="true" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity" v-show="quantityShow">
          <el-input v-model="form.quantity" placeholder="请输入数量" @input="onQuantityInput" :clearable="true" />
        </el-form-item>
        <el-form-item label="总金额" prop="amount" v-show="amountShow">
          <el-input v-model="form.amount" placeholder="请输入总金额" @input="onAmountInput" :clearable="true" />
        </el-form-item>
        <el-form-item label="手续费" prop="fee">
          <el-input v-model="form.fee" placeholder="请输入手续费" />
        </el-form-item>
        <!-- <el-form-item label="交易价格使用的日期" prop="priceDate">
          <el-date-picker clearable
            v-model="form.priceDate"
            type="datetime"
            :default-time="new Date(2000, 1, 1, 10, 0, 0)"
            placeholder="请选择交易价格使用的日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="与哪个账户进行转账" prop="transWith">
          <el-input v-model="form.transWith" placeholder="请输入与哪个账户进行转账" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="form.comment" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Transactions_fund" lang="ts">
import { listTransactions_fund, getTransactions_fund, delTransactions_fund, addTransactions_fund, updateTransactions_fund } from "@/app/finace/api/finace/transactions_fund";
import { listAccount } from "@/app/finace/api/finace/account";
import { listProduct } from "@/app/finace/api/finace/product";

import { getCurrentInstance, onMounted } from "vue";

const { proxy } = getCurrentInstance() || {};

import {
  accountList,
  productList,
  transactions_fundList,
  open,
  loading,
  showSearch,
  ids,
  single,
  multiple,
  total,
  title,
  autoCalcAmount,
  dividendType,
  soldOffSelected,
  userStore,
  userInfo,
  permissions,
  queryParams,
  form,
  rules,
  isCash,
  isDividend,
  quantityShow,
  amountShow,
} from './data'

import {
  onSoldOffSelectChange,
  onTradeTypeChanged,
  onRowClicked,
  onRadioChange,
  onPriceInput,
  onQuantityInput,
  onAmountInput,
  confirmDateChange,
  productIdChanged,
} from "./events"
import { copySelectionToForm } from "./utils";

/** 查询个人持仓记录列表 */
function getList() {
  loading.value = true;
  listTransactions_fund(queryParams.value).then(response => {
    console.log(response)
    transactions_fundList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    transactionId: null,
    userId: null,
    accountId: null,
    productId: null,
    submitTime: null,
    confirmDate: null,
    type: null,
    price: 0,
    quantity: 0,
    amount: 0,
    fee: 0,
    priceDate: null,
    transWith: null,
    comment: null
  };
  proxy.resetForm("transactions_fundRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log({ selection })
  ids.value = selection.map(item => item.transactionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // jm add 
  if (selection.length === 1) {
    copySelectionToForm(selection)
  }
  else {
    reset()
  }
}

/** 新增按钮操作 */
function handleAdd() {
  // reset();
  form.value.transactionId = null;
  open.value = true;
  title.value = "添加个人持仓记录";
  form.value.userId = userInfo.value.userId
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _transactionId = row.transactionId || ids.value
  getTransactions_fund(_transactionId).then(response => {
    console.log(response)
    form.value = response.data;
    open.value = true;
    title.value = "修改个人持仓记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["transactions_fundRef"].validate(valid => {
    if (valid) {
      setHiddenItemValueToZero()
      if (form.value.transactionId != null) {
        updateTransactions_fund(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTransactions_fund(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/**
 * 将隐藏项的值设置为0
 *
 * 如果隐藏项（quantityShow、amountShow）的值为true，则保留form中的quantity和amount的值；
 * 如果隐藏项的值为false，则将form中的quantity和amount的值设置为0。
 */
function setHiddenItemValueToZero() {
  form.value.quantity = quantityShow.value ? form.value.quantity : 0
  form.value.amount = amountShow.value ? form.value.amount : 0
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _transactionIds = row.transactionId || ids.value;
  proxy.$modal.confirm('是否确认删除个人持仓记录编号为"' + _transactionIds + '"的数据项？').then(function () {
    return delTransactions_fund(_transactionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('finace/transactions_fund/export', {
    ...queryParams.value
  }, `transactions_fund_${new Date().getTime()}.xlsx`)
}



onMounted(() => {
  loading.value = false
  userStore.getInfo().then((res) => {
    console.log({ res })
    userInfo.value = res.user
    permissions.value = res.permissions
    // getNowFund(userInfo.value.userId).then((res)=>{
    //     // console.log(res)
    //     tableData.value=res
    //     dbgmsg.value=res
    // })
    Promise.all([
      listAccount({ pageSize: 1000, }),
      listProduct({ pageSize: 1000, })
    ]).then((res) => {
      console.log(res)
      const [accountRes, ProductRes] = res
      accountList.value = accountRes.rows
      productList.value = ProductRes.rows
      loading.value = false
    }).then(() => {
      console.log(accountList)
      queryParams.value = {
        userId: userInfo.value.userId,
      }
      getList();
    })
  })
})

</script>
